package com.financing.wap.service.payment.biz;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.common.BizEnums;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.BankCardDTO;
import com.financing.wap.dto.BankInfoDTO;
import com.financing.wap.dto.FpBiddingReceiptDTO;
import com.financing.wap.dto.FpPaymentDTO;
import com.financing.wap.dto.FpYouDanAmountDetailDTO;
import com.financing.wap.dto.OrderDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IBankCardService;
import com.financing.wap.service.IBankInfoService;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IFpBiddingReceiptService;
import com.financing.wap.service.IFpPaymentbaofoorspService;
import com.financing.wap.service.IOrderService;
import com.financing.wap.service.IPaymentErrormsgService;
import com.financing.wap.service.IPaymentService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.payment.baofoo.BaofooService;
import com.financing.wap.service.payment.baofoo.demo.BaofuBindcardService;
import com.financing.wap.service.payment.baofoo.model.BaofooConfig;
import com.financing.wap.service.payment.baofoo.model.FpPaymentbaofoorsp;
import com.financing.wap.service.payment.baofoo.util.JSONUtils;
import com.financing.wap.util.BasicUtils;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.MoneyUtil;
import com.financing.wap.util.SequenceManagerNew;
import com.financing.wap.web.controller.api.SendOtpController;

/**
 * 宝付支付服务，包含业务逻辑
 * 
 * @author wade
 *
 */
@Service("paymentBaofooBizService")
public class PaymentBaofooBizService implements PaymentBizService {

	@Autowired
	private SendOtpController apiSendOtpController;

	@Autowired
	private IBankInfoService bankInfoServiceImpl;

	@Autowired
	private IPaymentService paymentServiceImpl;// 支付流水服务
	
	@Autowired
	private IFpPaymentbaofoorspService paymentbaofoorspServiceImpl;// 宝付支付响应服务
	
	@Autowired
	private ICommonService commonServiceImpl;// 公共服务
	
	@Autowired
	IFpBiddingReceiptService fpBiddingReceiptService;//竞价服务
	
	@Autowired
	private IUserService userService; //用户服务
	
	@Autowired
	private IBankCardService bankCardServiceImpl; //用户此卡服务
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IPaymentErrormsgService paymentErrormsgService;// 错误代码
	
	@Autowired
	private IProductService  productService;//产品服务
	
	


	private SimpleDateFormat sd = new SimpleDateFormat(
			BizEnums.CommonEnums.JUYOUBAO_DATE_PATTERN);// 聚友投平台日期格式
	private SimpleDateFormat sd2 = new SimpleDateFormat(
			BizEnums.CommonEnums.JUYOUBAO_DATE_PATTERN2);// 
	private final static Logger logger = LoggerFactory
			.getLogger(PaymentBaofooBizService.class.getClass());

	/**
	 * 宝付
	 */
	@Override
	public Map<String, String> invokebindbankcard(Map<String, String> auth)
			throws Exception {
		Map<String, String> temp = new HashMap<String, String>();

		String phone = auth.get("phone");// 手机号

		ResultMap resultMap = apiSendOtpController
				.sendMessageCodeByCardBinding(phone);

		temp.put("statusCode", resultMap.getStatusCode());
		if (ResultMap.STATUS.SUCCESS.equals(resultMap.getStatus())) {
			temp.put("status", "SUCCESS");
		} else {
			temp.put("status", "FAILE");
		}
		return temp;
	}

	@Override
	public Map<String, String> confirmbindbankcard(Map<String, String> auth)
			throws Exception {
		
		final String userRealName = auth.get("username");//持卡人姓名
		final String cardNum = auth.get("cardno");//银行卡号
		final String bankcode = auth.get("bankcode");//聚友投平台银行编码,可以根据支付商类型和该编码获取真实的通联的银行编码
		final String bankname = auth.get("bankname");//聚友投平台银行名称
		final String paperNo = auth.get("idcardno");//身份证号
		final String paperType = "0";//默认身份证类型
		final String phone = auth.get("phone");//银行预留的手机号
		final String smsCode = auth.get("validatecode");//短信验证码
		final String userId = auth.get("identityid");//用户编号
		String bind_id ="";

		Map<String, String> temp = new HashMap<String, String>();
		

		Date now = new Date();
		Date end = null;
		
		//根据支付商标识、聚友投平台统一编码获取对应的支付商银行信息
		BankInfoDTO  bankInfo =bankInfoServiceImpl.loadByParentcodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, bankcode);
		
		if(bankInfo==null){
			temp.put("status", "FAILE");
			temp.put("statusCode", ResultMap.STATUS_CODE_DOES_NOT_SET_BANKINFO);
			return temp;
		}

		//按支付提示补齐银行代码:
		String sendBankCode = bankInfo.getBankCode();
		
		boolean flag=false;
		
		//流水id
		String id = SequenceManagerNew.seq();
		{//发送验证
			
//			String mid="100000178";
//			String tid="100000859";
			String mid = BaofooConfig.getInstance().getMember_id();//商户号
			String tid = BaofooConfig.getInstance().getTerminal_id();//终端号
			String transno=id;
			String transid=id;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String datestr=sdf.format(new Date());
			
			String idholder=userRealName;
			String idcard=paperNo;
			String mobile=phone;
//			String bankcode="ABC";
			String acc_no=cardNum;
			JSONObject json=BaofuBindcardService.bindcard(mid, tid, transno, transid, datestr, idholder, idcard, mobile, sendBankCode, acc_no);
			String code = JSONUtils.getStr(json, "resp_code");
			bind_id = JSONUtils.getStr(json, "bind_id");
			if(StringUtils.equals(code, "0000")){
				flag=true;
			}
			end = new Date();
			temp.put("code", code);
			
			temp.put("msg", paymentErrormsgService.queryErrorMsgByErrorCodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, code));
		}
		
		final String bind_id_f =bind_id;
		
		
		//调用实名认证 登记到 FpPaymentDTO支付流水表中，便于日后对账使用 ，用“接口类型”区别开
		
		FpPaymentDTO payment = new FpPaymentDTO();
		payment.setPayId(id);//每笔订单一个支付流水，因此可重用ID
		payment.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
				BizEnums.PayEnums.PAY_3PLAT_BAOFOO));//平台流水号(加上支付商标识)
		payment.setOrderId(null);//订单编码 -> 认证无订单号
		payment.setInterfaceType(BizEnums.PayEnums.PAY_INTERFACE_TYPE_ACCTVERIFY);//实名认证
		payment.setPayDate(sd.format(now));//支付日期 -> 认证日期
		payment.setPayStartTime(now);//支付时间 -> 认证时间
		payment.setPayEndTime(end);//支付时间 -> 接口结束时间
		payment.setPayAmt(MoneyUtil.zero);//支付金额 -> 认证时为0
		payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
		payment.setOutAccount(cardNum);//资金扣出账户（用户个人账户）->认证时的银行账号
		payment.setInAccount(null);//资金存入账户 （朝阳永续指定账户）-> null
		payment.setTpay3plat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO);//目前只有一个支付供应商，默认通联
		payment.setPayDesc(new StringBuffer().append("实名认证:")
				.append("姓名=").append(userRealName)
				.append("电话=").append(phone)
				.append("身份证=").append(paperNo)
				.append("账号=").append(cardNum)
				.toString());//支付描述 -> 记录实名认证五要素
		payment.setExt1(phone);//记录用户手机号，也即是用户名
		payment.setExt2(paperNo);//记录用户真实身份证号
		payment.setExt3(cardNum);//记录用户真实银行卡号
		payment.setTpayRetCode(temp.get("code"));
		payment.setTpayRetMsg(temp.get("msg"));
		//payment.setPlat_serial_no(rest.reqNo);//认证请求流水号(宝付没有reqNO无需保存)
		payment.setTpayReSerialNo(bind_id_f);//认证请求流水号-通联直接返回);

		if(flag){
			//认证成功
			payment.setTpayResult("success");
			payment.setPayStatus(BizEnums.PayEnums.PAY_STATUS_SUCC);//支付状态-> 2验证成功
		}else{
			//认证失败
			payment.setTpayResult("fail");
			payment.setPayStatus(BizEnums.PayEnums.PAY_STATUS_FAIL);//支付状态-> 3验证失败
		}
		
		paymentServiceImpl.insertPayment(payment);//新增支付流水信息
		
		//如果认证不成功，则报错并返回
		if(!flag){
			temp.put("statusCode", temp.get("code"));
			temp.put("status", "FAILE");
			temp.put("errorMsg",temp.get("msg"));
			return temp;
		}
		//认证成功，则记录数据并返回成功
		//起事务，维护等级用户的银行卡信息、实名认证、维护人员认证信息及银行卡信息

		BankCardDTO bankCardDTO = new BankCardDTO();
		bankCardDTO.setUserId(userId);
		bankCardDTO.setBankName(bankname);
		bankCardDTO.setBankType(bankcode);
		bankCardDTO.setCardNumber(cardNum);
		bankCardDTO.setCardType("01");
		bankCardDTO.setPayPlat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO);
		bankCardDTO.setBindingDate(sd.format(now));
		bankCardDTO.setBindingTime(now);
		bankCardDTO.setIdenCode(smsCode);
		bankCardDTO.setOprPhone(phone);
		bankCardDTO.setIsDefault(BizEnums.UserEnums.USER_BINGDING_CARD_DEFAULT);
		bankCardDTO.setBindId(bind_id_f);
		bankCardDTO.setUserName(userRealName);
		bankCardDTO.setPaperNo(paperNo);
		DTOdateSetUtil.setCreateInfo(bankCardDTO);
		DTOdateSetUtil.setUpdateInfo(bankCardDTO);
		
		//wap_jee_1.53 支持多卡
		UserDTO userInfo = userService.queryUserById(userId);
		UserDTO user = new UserDTO();
		long bindingNum = userInfo.getBindingNum()==null?0:userInfo.getBindingNum();
		if(bindingNum>0){
			//已经绑卡过  数量+1
			++bindingNum;
			user.setId(userId);
			user.setBindingNum(bindingNum);//默认绑定银行卡张数为1张
		}else{
			//未绑定卡、修改用户信息，维护绑定的银行卡、实名认证信息			
			user.setId(userId);
			user.setBindingNum(1l);//默认绑定银行卡张数为1张
			user.setDefBingingCrad(cardNum);
			user.setDefCardBankCode(bankcode);//聚友投统一银行编码
			user.setIsRealNmae(BizEnums.UserEnums.USER_REALNAME_SUCCESS);//0-未认证（默认）,1-认证成功,2-认证失败
			user.setRealDate(sd.format(now));
			user.setRealTime(now);
			user.setRealPaperType(paperType);//默认为身份证
			user.setRealPaperNo(paperNo);//默认为身份证证件号码
			user.setRealRetMsg(temp.get("code"));//实名认证响应
		}
		String result = commonServiceImpl.confirmbindbankcard(bankCardDTO,user);
		
		if("SUCCESS".equals(result)){
			
			temp.put("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			temp.put("status", "SUCCESS");	
			temp.put("cardId", bankCardDTO.getId().toString());	
		}
		
		return temp;
	}

	@Override
	public Map<String, String> sendPayRequest(Map<String, String> payRequest)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, String> queryOrderStatus(Map<String, String> order)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, String> sendSMSRequest(Map<String, String> payRequest)
			throws Exception {
		
		Map<String, String> result = new HashMap<String, String>();
		
		
		return result;
	}

	@Override
	public Map<String, String> sendSMSRequestBZJ(Map<String, String> payRequest)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		
		String identityid = payRequest.get("identityid");//用户唯一标识
		String orderId = payRequest.get("orderid");//订单编码
		String cardId = payRequest.get("cardId");//卡id
		
		//订单金额
		FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
		dto.setBiddingCode(orderId);
		dto = fpBiddingReceiptService.queryFpBiddingReceiptInfo(dto);
		
		String amout = dto.getBailAmount().multiply(new BigDecimal("100"))
				.stripTrailingZeros().toPlainString();//金额分
		

		//3、查询 根据cardId_ 查询银行卡
		BankCardDTO bankCardDTOView = new BankCardDTO();
		bankCardDTOView.setId(Integer.valueOf(cardId));
		bankCardDTOView.setUserId(identityid);
		bankCardDTOView = bankCardServiceImpl.queryBankCard(bankCardDTOView);
		
		if(bankCardDTOView == null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_4017);
			return result;
		}
		String cardno = bankCardDTOView.getCardNumber();
		
		BankCardDTO bankCardDTO  = new BankCardDTO();
		bankCardDTO = bankCardDTOView;
	
		String phone  = bankCardDTO.getOprPhone();//获取银行卡号对应的绑定的手机号
		
		String bankcode = bankCardDTO.getBankType();

		
		//根据支付商标识、聚友投平台统一编码获取对应的支付商银行信息
		BankInfoDTO  bankInfo =bankInfoServiceImpl.loadByParentcodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, bankcode);
		
		if(bankInfo==null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_DOES_NOT_SET_BANKINFO);
			return result;
		}
		
		String baoFooBankcode = bankInfo.getBankCode();//获取宝付对应的真实银行编码
		String idcardno = bankCardDTO.getPaperNo();//身份证信息
		String userRealname = bankCardDTO.getUserName();//持卡人姓名
		String additionalInfo = "XXX产品名称" ; //附加信息：产品名称
		String bind_id = bankCardDTO.getBindId();
		
		//发送支付短信交易请求
		FpPaymentbaofoorsp baofoorsp = BaofooService.sendSMS(orderId, cardno, baoFooBankcode, phone, idcardno, userRealname, amout,bind_id,additionalInfo);
		
		//返回响应编码
		String status = baofoorsp.getResp_code();
		if("0000".equals(status)){//支付成功
			result.put("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			result.put("status", "SUCCESS");	
		}else{
			result.put("statusCode", ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.put("errorMsg", paymentErrormsgService.queryErrorMsgByErrorCodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, baofoorsp.getResp_code()));
			result.put("status", "FAILE");	
		}
		return result;
	}

	@Override
	public Map<String, String> sendPayRequestBZJ(Map<String, String> payRequest)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		
		String identityid = payRequest.get("identityid");//用户唯一标识
		String orderId = payRequest.get("orderid");//订单编码
		String smsCode = payRequest.get("smsCode");//短信
		String cardId = payRequest.get("cardId");//卡id
		String payPlatFinal = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//支付商标识
		Date now = new Date();
		
		//订单金额
		FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
		dto.setBiddingCode(orderId);
		dto = fpBiddingReceiptService.queryFpBiddingReceiptInfo(dto);
		
		String amout = dto.getBailAmount().multiply(new BigDecimal("100"))
				.stripTrailingZeros().toPlainString();//金额分
		
		ProductDetailPageDTO product = productService.getProductDetailPage(dto.getpId());
		String productName = product.getProductShortName();
		
		//3、查询 根据cardId_ 查询银行卡
		BankCardDTO bankCardDTOView = new BankCardDTO();
		bankCardDTOView.setId(Integer.valueOf(cardId));
		bankCardDTOView.setUserId(identityid);
		bankCardDTOView = bankCardServiceImpl.queryBankCard(bankCardDTOView);
		
		if(bankCardDTOView == null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_4017);
			return result;
		}
		String cardno = bankCardDTOView.getCardNumber();
		
		BankCardDTO bankCardDTO  = new BankCardDTO();
		bankCardDTO = bankCardDTOView;
	
		String phone  = bankCardDTO.getOprPhone();//获取银行卡号对应的绑定的手机号
		
		String bankcode = bankCardDTO.getBankType();
		
		//根据支付商标识、聚友投平台统一编码获取对应的支付商银行信息
		BankInfoDTO  bankInfo =bankInfoServiceImpl.loadByParentcodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, bankcode);
		
		if(bankInfo==null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_DOES_NOT_SET_BANKINFO);
			return result;
		}
		
		//调用支付保证金 登记到 FpPaymentDTO支付流水表中，便于日后对账使用 ，用“接口类型”区别开
		
		FpPaymentDTO payment = new FpPaymentDTO();
		payment.setPayId(dto.getId().toString());//每笔订单一个支付流水，因此可重用ID
		payment.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
				payPlatFinal));//平台流水号(加上支付商标识)
		payment.setOrderId(orderId);//订单编码
		payment.setInterfaceType(BizEnums.PayEnums.PAY_INTERFACE_TYPE_PAYBZJ);//支付
		payment.setPayDate(sd.format(now));//支付日期
		payment.setPayStartTime(now);
		payment.setPayAmt(dto.getBailAmount());//支付金额 = 订单总金额
		payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
		payment.setOutAccount(cardno);//资金扣出账户（用户个人账户）
		payment.setInAccount(BizEnums.CommonEnums.SUPERFA_FUND_ACCOUNT_NO);//资金存入账户 （朝阳永续指定账户）
		payment.setPayStatus(BizEnums.PayEnums.PAY_STATUS_NEW);//支付状态 待支付
		payment.setTpay3plat(payPlatFinal);//支付商标识
		payment.setPayDesc(productName);//支付描述
		payment.setCardCarrier(bankCardDTO.getUserName());//持卡人姓名
		payment.setUserId(identityid);//用户id
		payment.setCardNo(cardno);//持卡号
		payment.setPayMode(bankCardDTO.getBankName());//交易方式
		payment.setPayType("online");//支付类型（online,offline）
		DTOdateSetUtil.setCreateInfo(payment);
		DTOdateSetUtil.setUpdateInfo(payment);
		paymentServiceImpl.insertPayment(payment);//新增支付流水信息
		
		String baoFooBankcode = bankInfo.getBankCode();//获取宝付对应的真实银行编码
		String idcardno = bankCardDTO.getPaperNo();//身份证信息
		String userRealname = bankCardDTO.getUserName();//持卡人姓名
		String additionalInfo = "XXX产品名称" ; //附加信息：产品名称
		String bind_id = bankCardDTO.getBindId();
		
		//发送支付交易请求
		//Jnlpaymentbaofoorsp baofoorsp = BaofooService.sendQkPay(smsCode,orderId, cardno, baoFooBankcode, phone, idcardno, userRealname, amout,bind_id,additionalInfo);
		FpPaymentbaofoorsp baofoorsp = BaofooService.sendQkPay(smsCode,orderId, cardno, baoFooBankcode, phone, idcardno, userRealname, amout,bind_id,additionalInfo);
		
		baofoorsp.setReq_come_from("请求宝付支付接口同步返回");//响应流水来源
		baofoorsp.setReceive_time(new Date());//接收宝付支付返回时间
		DTOdateSetUtil.setCreateInfo(baofoorsp);
		DTOdateSetUtil.setUpdateInfo(baofoorsp);
		paymentbaofoorspServiceImpl.insertPaymentbaofoorsp(baofoorsp);//插入宝付支付流水表

		//记录平台的支付流水记录
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", payment.getId().toString());
		map.put("orderId", orderId);
		map.put("payStatus", BizEnums.PayEnums.PAY_STATUS_NEW);
		FpPaymentDTO paymentUp =  paymentServiceImpl.loadByOrderId(map);
		
		paymentUp.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
				BizEnums.PayEnums.PAY_3PLAT_BAOFOO));//平台流水号(加上支付商标识)
		paymentUp.setTpay3plat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO);//宝付支付
		paymentUp.setTpayReSerialNo(baofoorsp.getTrans_no());//宝付订单流水号
		paymentUp.setPayEndTime(new Date());//支付结束时间
		paymentUp.setTpayResult(baofoorsp.getResp_msg());//处理结果
		paymentUp.setTpayRetCode(baofoorsp.getResp_code());//支付错误码
		paymentUp.setTpayRetMsg(baofoorsp.getResp_msg());//支付错误信息

		
		
		//有单金额明细表  - 保证金冻结
		
		FpYouDanAmountDetailDTO youDanAmountDetailDTO = new FpYouDanAmountDetailDTO();
		youDanAmountDetailDTO.setAssociationId(dto.getId()+"");//竞价 id
		youDanAmountDetailDTO.setAmountType(BizEnums.YouDanAmountDetaiEnums.AMOUNT_TYPE_BZJ);
		youDanAmountDetailDTO.setOperateType(BizEnums.YouDanAmountDetaiEnums.OPERATE_TYPE_DJ);
		youDanAmountDetailDTO.setAmount(dto.getBailAmount());
		youDanAmountDetailDTO.setFaId(Integer.valueOf(identityid));
		DTOdateSetUtil.setCreateInfo(youDanAmountDetailDTO);
		DTOdateSetUtil.setUpdateInfo(youDanAmountDetailDTO);
		
		//根据支付结果进行相应处理, 公共处理方法
		if( "0000".equals(baofoorsp.getResp_code()) ){//表示成功
			
			commonServiceImpl.orderBZJDealSuccessNew(dto,paymentUp,youDanAmountDetailDTO);//订单支付成功
			result.put("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			result.put("status", "SUCCESS");	
			
			//返回-支付金额、支付内容、支付金额、支付方式、交易时间、交易单号
			result.put("amount", dto.getBailAmount().toString());
			result.put("content", "保证金");
			result.put("mode", bankCardDTO.getBankName());
			result.put("time", sd2.format(now));
			result.put("number", payment.getPlatSerialNo());
			result.put("productName", productName);
			result.put("cardNumber", cardno);
			
			
		}else{//处理失败
			commonServiceImpl.orderBZJDealFailNew(dto, paymentUp);//订单支付失败
			result.put("statusCode", ResultMap.STATUS_CODE_4014);
			result.put("errorMsg", paymentErrormsgService.queryErrorMsgByErrorCodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, baofoorsp.getResp_code()));
			result.put("status", "FAIL");	
		}
		
		return result;
	}

	@Override
	public Map<String, String> sendPayRequestYJ(Map<String, String> payRequest)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		
		String identityid = payRequest.get("identityid");//用户唯一标识
		String orderId = payRequest.get("orderid");//订单编码
		String smsCode = payRequest.get("smsCode");//短信
		String cardId = payRequest.get("cardId");//卡id
		String payPlatFinal = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//支付商标识
		Date now = new Date();
		
		//订单金额
		//查询订单
		OrderDTO orderDTO = orderService.getOrder(orderId);

		String amout = orderDTO.getoYouDanRebate().multiply(new BigDecimal("100"))
				.stripTrailingZeros().toPlainString();//金额分
		
		//3、查询 根据cardId_ 查询银行卡
		BankCardDTO bankCardDTOView = new BankCardDTO();
		bankCardDTOView.setId(Integer.valueOf(cardId));
		bankCardDTOView.setUserId(identityid);
		bankCardDTOView = bankCardServiceImpl.queryBankCard(bankCardDTOView);
		
		if(bankCardDTOView == null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_4017);
			return result;
		}
		String cardno = bankCardDTOView.getCardNumber();
		
		BankCardDTO bankCardDTO  = new BankCardDTO();
		bankCardDTO = bankCardDTOView;
	
		String phone  = bankCardDTO.getOprPhone();//获取银行卡号对应的绑定的手机号
		
		String bankcode = bankCardDTO.getBankType();
		
		//根据支付商标识、聚友投平台统一编码获取对应的支付商银行信息
		BankInfoDTO  bankInfo =bankInfoServiceImpl.loadByParentcodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, bankcode);
		
		if(bankInfo==null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_DOES_NOT_SET_BANKINFO);
			return result;
		}
		
		//调用支付保证金 登记到 FpPaymentDTO支付流水表中，便于日后对账使用 ，用“接口类型”区别开
		
		FpPaymentDTO payment = new FpPaymentDTO();
		payment.setPayId(orderDTO.getId().toString());//每笔订单一个支付流水，因此可重用ID
		payment.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
				payPlatFinal));//平台流水号(加上支付商标识)
		payment.setOrderId(orderDTO.getOrderCode());//订单编码
		payment.setInterfaceType(BizEnums.PayEnums.PAY_INTERFACE_TYPE_PAYYJ);//支付
		payment.setPayDate(sd.format(now));//支付日期
		payment.setPayStartTime(now);
		payment.setPayAmt(orderDTO.getoYouDanRebate());//支付金额 = 订单总金额
		payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
		payment.setOutAccount(cardno);//资金扣出账户（用户个人账户）
		payment.setInAccount(BizEnums.CommonEnums.SUPERFA_FUND_ACCOUNT_NO);//资金存入账户 （朝阳永续指定账户）
		payment.setPayStatus(BizEnums.PayEnums.PAY_STATUS_NEW);//支付状态 待支付
		payment.setTpay3plat(payPlatFinal);//支付商标识
		payment.setPayDesc(orderDTO.getpName());//支付描述
		payment.setCardCarrier(bankCardDTO.getUserName());//持卡人姓名
		payment.setUserId(identityid);//用户id
		payment.setCardNo(cardno);//持卡号
		payment.setPayMode(bankCardDTO.getBankName());//交易方式
		payment.setPayType("online");//支付类型（online,offline）
		DTOdateSetUtil.setCreateInfo(payment);
		DTOdateSetUtil.setUpdateInfo(payment);
		paymentServiceImpl.insertPayment(payment);//新增支付流水信息
		
		String baoFooBankcode = bankInfo.getBankCode();//获取宝付对应的真实银行编码
		String idcardno = bankCardDTO.getPaperNo();//身份证信息
		String userRealname = bankCardDTO.getUserName();//持卡人姓名
		String additionalInfo = "产品名称:"+orderDTO.getpName() ; //附加信息：产品名称
		String bind_id = bankCardDTO.getBindId();
		
		//发送支付交易请求
		//Jnlpaymentbaofoorsp baofoorsp = BaofooService.sendQkPay(smsCode,orderId, cardno, baoFooBankcode, phone, idcardno, userRealname, amout,bind_id,additionalInfo);
		FpPaymentbaofoorsp baofoorsp = BaofooService.sendQkPay(smsCode,orderDTO.getOrderCode(), cardno, baoFooBankcode, phone, idcardno, userRealname, "1",bind_id,additionalInfo);
		
		baofoorsp.setReq_come_from("请求宝付支付接口同步返回");//响应流水来源
		baofoorsp.setReceive_time(new Date());//接收宝付支付返回时间
		DTOdateSetUtil.setCreateInfo(baofoorsp);
		DTOdateSetUtil.setUpdateInfo(baofoorsp);
		paymentbaofoorspServiceImpl.insertPaymentbaofoorsp(baofoorsp);//插入宝付支付流水表

		//记录平台的支付流水记录
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", payment.getId().toString());
		//map.put("orderId", orderId);
		//map.put("payStatus", BizEnums.PayEnums.PAY_STATUS_NEW);
		FpPaymentDTO paymentUp =  paymentServiceImpl.loadByOrderId(map);
		
		paymentUp.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
				BizEnums.PayEnums.PAY_3PLAT_BAOFOO));//平台流水号(加上支付商标识)
		paymentUp.setTpay3plat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO);//宝付支付
		paymentUp.setTpayReSerialNo(baofoorsp.getTrans_no());//宝付订单流水号
		paymentUp.setPayEndTime(new Date());//支付结束时间
		paymentUp.setTpayResult(baofoorsp.getResp_msg());//处理结果
		paymentUp.setTpayRetCode(baofoorsp.getResp_code());//支付错误码
		paymentUp.setTpayRetMsg(baofoorsp.getResp_msg());//支付错误信息

		
		
		//有单金额明细表  - 保证金冻结
		
		FpYouDanAmountDetailDTO youDanAmountDetailDTO = new FpYouDanAmountDetailDTO();
		youDanAmountDetailDTO.setAssociationId(orderDTO.getId());//竞价 id
		youDanAmountDetailDTO.setAmountType(BizEnums.YouDanAmountDetaiEnums.AMOUNT_TYPE_YJ);
		youDanAmountDetailDTO.setOperateType(BizEnums.YouDanAmountDetaiEnums.OPERATE_TYPE_DJ);
		youDanAmountDetailDTO.setAmount(orderDTO.getoYouDanRebate());
		youDanAmountDetailDTO.setFaId(Integer.valueOf(identityid));
		DTOdateSetUtil.setCreateInfo(youDanAmountDetailDTO);
		DTOdateSetUtil.setUpdateInfo(youDanAmountDetailDTO);
		
		//根据支付结果进行相应处理, 公共处理方法
		if( "0000".equals(baofoorsp.getResp_code()) ){//表示成功
			
			OrderDTO updateUorder = new OrderDTO();
			DTOdateSetUtil.setUpdateInfo(updateUorder);
			updateUorder.setId(orderDTO.getId());
			updateUorder.setoYouDanReceivedRebate(orderDTO.getoYouDanRebate());
			commonServiceImpl.orderYJDealSuccessNew(updateUorder,paymentUp,youDanAmountDetailDTO);//订单支付成功
			result.put("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			result.put("status", "SUCCESS");	
			
			//返回-支付金额、支付内容、支付金额、支付方式、交易时间、交易单号
			result.put("amount", orderDTO.getoYouDanRebate().toString());
			result.put("content", "佣金");
			result.put("mode", bankCardDTO.getBankName());
			result.put("time", sd2.format(now));
			result.put("number", payment.getPlatSerialNo());
			result.put("cardNumber", cardno);
			
		}else{//处理失败
			commonServiceImpl.orderYJDealFailNew(orderDTO, paymentUp);//订单支付失败
			result.put("statusCode", ResultMap.STATUS_CODE_4014);
			result.put("errorMsg", paymentErrormsgService.queryErrorMsgByErrorCodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, baofoorsp.getResp_code()));
			result.put("status", "FAIL");	
		}
		
		return result;
	}

	@Override
	public Map<String, String> sendSMSRequestYJ(Map<String, String> payRequest)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		
		String identityid = payRequest.get("identityid");//用户唯一标识
		String orderId = payRequest.get("orderid");//订单编码
		String cardId = payRequest.get("cardId");//卡id
		
		//查询订单
		OrderDTO orderDTO = orderService.getOrder(orderId);

		String amout = orderDTO.getoYouDanRebate().multiply(new BigDecimal("100"))
				.stripTrailingZeros().toPlainString();//金额分
		
		//3、查询 根据cardId_ 查询银行卡
		BankCardDTO bankCardDTOView = new BankCardDTO();
		bankCardDTOView.setId(Integer.valueOf(cardId));
		bankCardDTOView.setUserId(identityid);
		bankCardDTOView = bankCardServiceImpl.queryBankCard(bankCardDTOView);
		
		if(bankCardDTOView == null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_4017);
			return result;
		}
		String cardno = bankCardDTOView.getCardNumber();
		
		BankCardDTO bankCardDTO  = new BankCardDTO();
		bankCardDTO = bankCardDTOView;
	
		String phone  = bankCardDTO.getOprPhone();//获取银行卡号对应的绑定的手机号
		
		String bankcode = bankCardDTO.getBankType();

		
		//根据支付商标识、聚友投平台统一编码获取对应的支付商银行信息
		BankInfoDTO  bankInfo =bankInfoServiceImpl.loadByParentcodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, bankcode);
		
		if(bankInfo==null){
			result.put("status", "FAILE");
			result.put("statusCode", ResultMap.STATUS_CODE_DOES_NOT_SET_BANKINFO);
			return result;
		}
		
		String baoFooBankcode = bankInfo.getBankCode();//获取宝付对应的真实银行编码
		String idcardno = bankCardDTO.getPaperNo();//身份证信息
		String userRealname = bankCardDTO.getUserName();//持卡人姓名
		String additionalInfo = "产品名称:"+orderDTO.getpName() ; //附加信息：产品名称
		String bind_id = bankCardDTO.getBindId();
		
		//发送支付短信交易请求
		FpPaymentbaofoorsp baofoorsp = BaofooService.sendSMS(orderDTO.getOrderCode(), cardno, baoFooBankcode, phone, idcardno, userRealname, amout,bind_id,additionalInfo);
		
		//返回响应编码
		String status = baofoorsp.getResp_code();
		if("0000".equals(status)){//支付成功
			result.put("statusCode", ResultMap.STATUS_CODE_SUCCESS);
			result.put("status", "SUCCESS");	
		}else{
			result.put("statusCode", ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.put("errorMsg", paymentErrormsgService.queryErrorMsgByErrorCodeAndPayplat(BizEnums.PayEnums.PAY_3PLAT_BAOFOO, baofoorsp.getResp_code()));
			result.put("status", "FAILE");	
		}
		return result;
	}

}
